let preUrl
const { prodRequestUrl, testRequestUrl } = require('../../var')

if (process.env.CMS_ENV) {
  preUrl = testRequestUrl
} else {
  preUrl = prodRequestUrl
}

import http from './http'
import { Indicator, Toast } from 'mint-ui'

// 判断一个数是否在数量里面
const in_array = (single, arr) => {
  let i = 0,
    n = arr.length
  for (; i < n; ++i) if (arr[i] === single) return i
  return false
}

// 多维数组 => 单维
const getSingleProperty = (arr, name) => {
  let newArr = []
  arr.forEach(item => {
    newArr.push(item[name])
  })
  return newArr
}
import localStorageApi from './localStorageApi'

const request = ({
  method = 'get',
  url,
  loading = true, // 请求接口是否显示加载laoding
  errorTip = false, // status ！== 0 开启错误弹窗
  customMsg = [], // 自定义status对应的报错信息
  statusNoToast = [] // 没有默认弹窗的status数组
} = {}) => {
  return function(params = {}) {
    let axios
    const realUrl = preUrl + url
    const token = localStorageApi.get('access_token')
    if (loading) {
      Indicator.open({
        text: '加载中...',
        spinnerType: 'triple-bounce'
      })
    }
    axios = http({
      method,
      url: realUrl,
      params,
      data: params,
      headers: {
        Authorization: `Bearer ${token}`
      }
    })

    return axios
      .then(({ data }) => {
        if (loading) Indicator.close()
        if (!data.hasOwnProperty('data')) {
          // 非标准格式接口
          return data
        }
        if (data.code == 0) {
          return data.data
        }
        if (errorTip && in_array(data.code, statusNoToast) === false) {
          const statusArr = getSingleProperty(customMsg, 'status')
          const inArray = in_array(data.code, statusArr)
          if (inArray === false) {
            Toast(data.message)
          } else {
            // 当前返回status在自定义的报错里面
            Toast(customMsg[inArray].message)
          }
        }
        return Promise.reject({
          status: data.code,
          errMsg: data.message
        })
      })
      .catch(() => {
        if (loading) Indicator.close()
      })
  }
}

export default request
